namespace ChumChase.Model
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Reflection;

    public class FeedProviderCatalog : IFeedProviderCatalog
    {
        private readonly List<IFeedProvider> _providers = new List<IFeedProvider>();

        public FeedProviderCatalog()
        {
            ScanFolderForPlugsin();
        }

        public IList<IFeedProvider> Providers
        {
            get { return _providers; }
        }

        private void ScanFolderForPlugsin()
        {
            string path = Path.Combine(Environment.CurrentDirectory, "Providers");
            string[] files = Directory.GetFiles(path, "ChumChase.*.dll");

            IEnumerable<Type> types = from file in files
                                      let assm = Assembly.LoadFrom(file)
                                      from type in assm.GetExportedTypes()
                                      where typeof (IFeedProvider).IsAssignableFrom(type)
                                      select type;

            foreach (Type type in types)
            {
                var instance = (IFeedProvider) Activator.CreateInstance(type);
                _providers.Add(instance);
            }
        }
    }
}